package com.realbrand.net.realbrandpay.ui.activity.wallet.set;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IPhoneLogin;
import com.realbrand.net.realbrandpay.inter.IVerifyAuthCode;
import com.realbrand.net.realbrandpay.ui.activity.wallet.personer.BoundPhoneActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/7/10.
 */

public class VerifyPhoneCodeActivity extends BaseActivity {
    @BindView(R.id.phonecode_toolbar)
    Toolbar phonecodeToolbar;
    @BindView(R.id.verifyPhoneCode_bt_next)
    Button verifyPhoneCodeBtNext;
    @BindView(R.id.verifyPhoneCode_bt_sendPhoneCode)
    Button verifyPhoneCodeBtSendPhoneCode;
    @BindView(R.id.verifyPhoneCode_tv_text)
    TextView verifyPhoneCodeTvText;
    @BindView(R.id.verifyPhoneCode_et_VerifyCode)
    EditText verifyPhoneCodeEtVerifyCode;

    //用户手机号
    private String UserMobile;
    //请求获取的验证码
    private String verifyCode;
    //用户输入的验证码
    private String verifyCodeByUser;

    //定时器
    private TimeCount time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        phonecodeToolbar.setTitle("");
        phonecodeToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(phonecodeToolbar);
        phonecodeToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(VerifyPhoneCodeActivity.this, BoundPhoneActivity.class));
                finish();
            }
        });
        UserMobile = getIntent().getStringExtra("mobile");
        verifyPhoneCodeTvText.setText("请输入" + UserMobile + "收到的短信验证码");
        if (!verifyPhoneCodeBtSendPhoneCode.isClickable()) {
            verifyPhoneCodeBtSendPhoneCode.setClickable(true);
        }
        time = new TimeCount(120000, 1000);
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.verifyphonecode_activity;
    }

    @Override
    protected void setOnClick() {
        verifyPhoneCodeBtNext.setOnClickListener(this);
        verifyPhoneCodeBtSendPhoneCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //下一步
            case R.id.verifyPhoneCode_bt_next:
                //获取用户输入的验证码，然后做对比
                verifyCodeByUser = verifyPhoneCodeEtVerifyCode.getText().toString();
                if (TextUtils.isEmpty(verifyCodeByUser)) {
                    Static.toast(VerifyPhoneCodeActivity.this, "请输入收到的验证码");
                } else {
//                    if (verifyCode == null) {
//                        Static.toast(this, "验证码已过时，请重新获取验证码");
//                    } else {
//                        if (verifyCode.equals(verifyCodeByUser)) {
//                            //跳转到验证新手机
//                            Intent intent = new Intent(VerifyPhoneCodeActivity.this, VerifyNewPhoneActivity.class);
//                            intent.putExtra("userMobile", UserMobile);
//                            startActivity(intent);
//                        } else {
//                            Static.toast(VerifyPhoneCodeActivity.this, "请输入正确的验证码");
//                        }
//                    }
                    verifyAuthCode(verifyCodeByUser);
                }

                break;
            //发送验证码
            case R.id.verifyPhoneCode_bt_sendPhoneCode:
                verifyPhoneCodeBtSendPhoneCode.setClickable(false);
                getVerificationCode(UserMobile);

                break;
        }
    }

    private void verifyAuthCode(String verifyCodeByUser) {
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("METHOD", "GetAuthCode");
            jsonObject.put("SOURCE", "VerifyPhoneCodeActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("UserMobile", UserMobile);
            jsonObject.put("Verification", verifyCodeByUser);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IVerifyAuthCode iVerifyAuthCode = retrofit.create(IVerifyAuthCode.class);
            Call<ResponseBody> call = iVerifyAuthCode.verifyAuthCode(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(VerifyPhoneCodeActivity.this, "网络繁忙");
                    } else {
                        try {
                            String result = response.body().string();
                            L.d(L.TAG, "result" + result);
                            try {
                                JSONObject object = new JSONObject(result);
                                JSONArray data = object.getJSONArray("DATA");
                                JSONObject jsonObject1 = data.getJSONObject(0);
                                String string = jsonObject1.getString("result");
                                if ("true".equals(string)) {
                                    //c成功
                                    Intent intent = new Intent(VerifyPhoneCodeActivity.this, VerifyNewPhoneActivity.class);
                                    intent.putExtra("userMobile", UserMobile);
                                    startActivity(intent);
                                    finish();
                                } else if ("验证码已过时".equals(string)) {
                                    Static.toast(VerifyPhoneCodeActivity.this, "验证码已超时");

                                } else if ("验证码错误".equals(string)) {
                                    Static.toast(VerifyPhoneCodeActivity.this, "验证码错误");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getVerificationCode(String userMobile) {

        JSONObject object = new JSONObject();
        try {
            object.put("METHOD", "GetAuthCode");
            object.put("SOURCE", "VerifyPhoneCodeActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("UserMobile", userMobile);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(HTTPAPI.BASE_URL)
                    .build();
            IPhoneLogin getCode = retrofit.create(IPhoneLogin.class);
            Call<ResponseBody> call = getCode.phoneLogin(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String reault = response.body().string();
                        //验证码
                        verifyCode = new JSONObject(reault).getString("Verification");
                        Log.d("zhu", "收到的验证码" + verifyCode);
                        time.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    verifyPhoneCodeBtSendPhoneCode.setClickable(true);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            verifyPhoneCodeBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            verifyPhoneCodeBtSendPhoneCode.setClickable(false);
            verifyPhoneCodeBtSendPhoneCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }

        @Override
        public void onFinish() {
            verifyPhoneCodeBtSendPhoneCode.setText("重新获取验证码");
            verifyPhoneCodeBtSendPhoneCode.setClickable(true);
            verifyPhoneCodeBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            verifyCode = null;
        }
    }
}
